package io.xccit.config;

import org.apache.catalina.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * @author CH_ywx
 * @date 2023-06-04
 * @description
 */
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailsService userDetailsService;
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(userDetailsService).passwordEncoder(passwordEncoder());
    }

    @Bean
    public PasswordEncoder passwordEncoder(){
        return new BCryptPasswordEncoder();
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.formLogin() //标识登录页面由自己编写
                .loginPage("/login.html") //登录页面
                .loginProcessingUrl("/user/login") //用户登录url
                .defaultSuccessUrl("/test/index").permitAll() // 登录成功之后默认跳转的路径
                .and()
                .authorizeRequests().antMatchers("/","/test/hello").permitAll() // 设置哪些路径可以不用登录直接访问
                .anyRequest().authenticated()
                .and().csrf().disable(); //关闭csrf防护
    }
}
